﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;

namespace JTest.GUI
{
    public partial class frmListenPractice : Form
    {
        List<JTest.Others.ListenQuestion> PracticeList = new List<Others.ListenQuestion>();
        string strLevel = String.Empty;
        string strTopic = String.Empty;
        int currentIndex = -1;
        int colorIndex = 0;
        Brush CusBrush = Brushes.Black;
        List<Brush> myBrushList = new List<Brush>();
        int answered = 0;
        int trueAns = 0;
        List<string> CheckedYears = new List<string>();
        List<string> allPracList = new List<string>();

        string message1 = "";
        string message3 = "";
        string thongtin = "";
        string filelog = "";
        string luufile = "";
        string message2 = "";
        string baoloi = "";
        string strNoScript = "";
        /// <summary>
        /// Draws the color of the item with.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DrawItemEventArgs"/> instance containing the event data.</param>
        private void DrawItemWithColor(object sender, System.Windows.Forms.DrawItemEventArgs e)
        {

            // Draw the background of the ListBox control for each item.
            // Create a new Brush and initialize to a Black colored brush
            // by default.

            e.DrawBackground();
            Brush myBrush = myBrushList[e.Index];

            e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(),
            e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);

            // If the ListBox has focus, draw a focus rectangle 
            // around the selected item.

            e.DrawFocusRectangle();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="frmListenPractice"/> class.
        /// </summary>
        /// <param name="Level">The level.</param>
        /// <param name="Topic">The topic.</param>
        public frmListenPractice(string Level, string Topic)
        {
            InitializeComponent();
            controlLang();
            textTrueAns.Text = "";
            textNumOfQue.Text = "";
            this.listBoxQuestion.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
            this.listBoxQuestion.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.DrawItemWithColor);

            textLevel.Text = strLevel = Level;
            textTopic.Text = strTopic = Topic;
            if (Topic == "All topic")
            {
                allPracList = command.getListFilesInDir(Constant.MediaPath + Level , "*.mp3", System.IO.SearchOption.AllDirectories);
            }
            else
            allPracList = command.getListFilesInDir(Constant.MediaPath + Level + "\\" + Topic, "*.mp3", System.IO.SearchOption.AllDirectories);
            Regex regex = new Regex("\\d\\d\\d\\d", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
            Match M;
            for (int i = 0; i < allPracList.Count; i++)
            {
                string s = allPracList[i];
                s = s.Remove(0, s.Length - (s.Length - s.LastIndexOf(@"\")) + 1);

                regex = new Regex("\\d\\d\\d\\d", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                M = regex.Match(s);
                if (!checkedListBoxYeard.Items.Contains(M.Value))
                {
                    checkedListBoxYeard.Items.Add(M.Value);
                }
            }
        }
        /// <summary>
        /// @nhannc
        /// </summary>
        private void controlLang()
        {
            try
            {
                XmlNodeList xnList = frmMain.xml.SelectNodes("lang/listenpractice");
                foreach (XmlNode xn in xnList)
                {
                    this.Text = xn["title"].InnerText;
                    dockContainerItem1.Text = xn["bangdieukhien"].InnerText;
                    labLevel.Text = xn["capdo"].InnerText;
                    labTopic.Text = xn["chude"].InnerText;
                    labelNumOfQue.Text = xn["socauhoi"].InnerText;
                    labTrueAns.Text=xn["traloidung"].InnerText;
                    message3 = xn["message3"].InnerText;

                    groupPanelAnswer.Text = xn["cautraloi"].InnerText;
                    checkBoxShowKey.Text = xn["tuhiendapan"].InnerText;
                    butShowAnswer.Text = xn["dapan"].InnerText;
                    butExits.Text = xn["thoat"].InnerText;

                    dockContainerItem3.Text = xn["cauhoi"].InnerText;
                    dockContainerItem2.Text = xn["loithoai"].InnerText;

                    message1 = xn["message1"].InnerText;
                    thongtin = xn["thongtin"].InnerText;
                    filelog = xn["filelog"].InnerText;
                    luufile = xn["luufile"].InnerText;
                    message2 = xn["message2"].InnerText;
                    baoloi = xn["baoloi"].InnerText;
                    Constant.listenSentence = xn["cau"].InnerText;
                    strNoScript = xn["khongcoloithoai"].InnerText;
                    labelXNoImageMess.Text = xn["khonghinh"].InnerText;
                    expandablePanel1.TitleText = xn["Catalogue"].InnerText;
                    groupPanelMondai.Text = xn["loaicauhoi"].InnerText;
                    butStart.Text = xn["batdau"].InnerText;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Handles the Load event of the frmListenPractice control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void frmListenPractice_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the listBoxQuestion control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void listBoxQuestion_SelectedIndexChanged(object sender, EventArgs e)
        {
            resetAnswers();
            labelXNoImageMess.Visible = false;
            bar1.AutoHide = true;
            expandablePanel1.Expanded = false;

            currentIndex = listBoxQuestion.SelectedIndex;
            string strMp3URL = PracticeList[currentIndex].strfileName;
            // load image.
            string strImageUrl = strMp3URL.Remove(strMp3URL.Length - 3) + "gif";
            if (File.Exists(strImageUrl))
            {
                picQuestion.ImageLocation = strImageUrl;
            }
            else
            {
                strImageUrl = strMp3URL.Remove(strMp3URL.Length - 3) + "jpg";
                if (File.Exists(strImageUrl))
                    picQuestion.ImageLocation = strImageUrl;
                else
                {
                    picQuestion.ImageLocation = null;
                    labelXNoImageMess.Visible = true;
                }

            }


            // Load script

            string strScriptUrl = strMp3URL.Remove(strMp3URL.Length - 3) + "rtf";
            if (File.Exists(strScriptUrl))
            {
                richTextBoxScript.LoadFile(strScriptUrl);
                
            }
            else
            {
                strScriptUrl = strMp3URL.Remove(strMp3URL.Length - 3) + "txt";
                if (File.Exists(strScriptUrl))
                {
                    richTextBoxScript.LoadFile(strScriptUrl);
                }
                else
                {
                    richTextBoxScript.Text = strNoScript;
                }
            }

            axWMP.URL = strMp3URL;
            axWMP.Ctlcontrols.stop();

            if (String.Compare(PracticeList[listBoxQuestion.SelectedIndex].strAnswer, String.Empty) == 0) //chưa chọn câu trả lời
            {

                enableAllRadios();
                axWMP.Ctlcontrols.play();
            }
            else// đã chọn câu trả lời.
            {
                disableAllRadios();
                axWMP.Ctlcontrols.pause();
                Color color = Color.Brown;
                if (PracticeList[listBoxQuestion.SelectedIndex].isTrue() == 1)
                {
                    color = Color.Blue;
                }
                string answered = PracticeList[listBoxQuestion.SelectedIndex].strAnswer;

                if (String.Compare(answered, "1") == 0)
                {
                    radAnswer1.BackColor = color;
                }
                else if (String.Compare(answered, "2") == 0)
                {
                    radAnswer2.BackColor = color;
                }
                else if (String.Compare(answered, "3") == 0)
                {
                    radAnswer3.BackColor = color;
                }
                else if (String.Compare(answered, "4") == 0)
                {
                    radAnswer4.BackColor = color;
                }
                butShowAnswer_Click(sender, e);
            }
        }

        /// <summary>
        /// Resets the answers.
        /// </summary>
        private void resetAnswers()
        {
            radAnswer1.Checked = false;
            radAnswer1.ForeColor = Color.Black;
            radAnswer1.BackColor = Color.Transparent;
            radAnswer2.Checked = false;
            radAnswer2.ForeColor = Color.Black;
            radAnswer2.BackColor = Color.Transparent;
            radAnswer3.Checked = false;
            radAnswer3.ForeColor = Color.Black;
            radAnswer3.BackColor = Color.Transparent;
            radAnswer4.Checked = false;
            radAnswer4.ForeColor = Color.Black;
            radAnswer4.BackColor = Color.Transparent;
        }

        /// <summary>
        /// Handles the CheckedChanged event of the radAnswer1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void radAnswer1_CheckedChanged(object sender, EventArgs e)
        {
            if (radAnswer1.Checked)
            {
                string strAns = "1";
                setAns(strAns);
            }
        }

        private void setAns(string strAns)
        {
            axWMP.Ctlcontrols.pause();
            answered++;
            {
                PracticeList[listBoxQuestion.SelectedIndex].strAnswer = strAns;
                if (PracticeList[listBoxQuestion.SelectedIndex].isTrue() == 1)
                {
                    setBrush(listBoxQuestion.SelectedIndex, true);
                    radAnswer1.ForeColor = Color.Blue;
                    trueAns++;
                }
                else
                {
                    setBrush(listBoxQuestion.SelectedIndex, false);
                    radAnswer1.ForeColor = Color.Red;
                }
                this.disableAllRadios();
            }
            textTrueAns.Text = trueAns.ToString() + "/" + answered.ToString();
            if (checkBoxShowKey.Checked)
            {
                showAnswer();
            }
        }

        /// <summary>
        /// Handles the CheckedChanged event of the radAnswer2 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void radAnswer2_CheckedChanged(object sender, EventArgs e)
        {
            if (radAnswer2.Checked)
            {
                string strAns = "2";
                setAns(strAns);
            }
        }

        /// <summary>
        /// Handles the CheckedChanged event of the radAnswer3 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void radAnswer3_CheckedChanged(object sender, EventArgs e)
        {
            if (radAnswer3.Checked)
            {
                string strAns = "3";
                setAns(strAns);
            }
        }

        /// <summary>
        /// Handles the CheckedChanged event of the radAnswer4 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void radAnswer4_CheckedChanged(object sender, EventArgs e)
        {
            if (radAnswer4.Checked)
            {
                string strAns = "4";
                setAns(strAns);
            }
        }

        /// <summary>
        /// Handles the Click event of the butShowAnswer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void butShowAnswer_Click(object sender, EventArgs e)
        {
            showAnswer();
        }

        private void showAnswer()
        {
            axWMP.Ctlcontrols.pause();
            string answer = PracticeList[listBoxQuestion.SelectedIndex].strKey;
            if (String.Compare(answer, "1") == 0)
            {
                radAnswer1.BackColor = Color.Blue;
            }
            else if (String.Compare(answer, "2") == 0)
            {
                radAnswer2.BackColor = Color.Blue;
            }
            else if (String.Compare(answer, "3") == 0)
            {
                radAnswer3.BackColor = Color.Blue;
            }
            else
            {
                radAnswer4.BackColor = Color.Blue;
            }
            if (PracticeList[listBoxQuestion.SelectedIndex].isTrue() != 1)
                setBrush(listBoxQuestion.SelectedIndex, false);
            if (String.Compare(PracticeList[listBoxQuestion.SelectedIndex].strAnswer, String.Empty) == 0 || String.Compare(PracticeList[listBoxQuestion.SelectedIndex].strAnswer, "-1") == 0)
            {
                myBrushList[listBoxQuestion.SelectedIndex] = Brushes.Green;
            }
            disableAllRadios();
            if (String.Compare(PracticeList[listBoxQuestion.SelectedIndex].strAnswer, String.Empty) == 0)
            {
                PracticeList[listBoxQuestion.SelectedIndex].strAnswer = "-1";
            }
        }

        /// <summary>
        /// Sets the brush.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="isTrue">if set to <c>true</c> [is true].</param>
        private void setBrush(int index, bool isTrue)
        {
            if (isTrue)
            {
                myBrushList[listBoxQuestion.SelectedIndex] = Brushes.Blue;

            }
            else
            {
                myBrushList[listBoxQuestion.SelectedIndex] = Brushes.Red;
            }
            colorIndex = listBoxQuestion.SelectedIndex;
            this.listBoxQuestion.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.DrawItemWithColor);
        }


        /// <summary>
        /// Disables all radios.
        /// </summary>
        private void disableAllRadios()
        {
            radAnswer1.Enabled = false;
            radAnswer2.Enabled = false;
            radAnswer3.Enabled = false;
            radAnswer4.Enabled = false;
        }

        /// <summary>
        /// Enables all radios.
        /// </summary>
        private void enableAllRadios()
        {
            radAnswer1.Enabled = true;
            radAnswer2.Enabled = true;
            radAnswer3.Enabled = true;
            radAnswer4.Enabled = true;
        }

        /// <summary>
        /// Handles the Click event of the butExits control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void butExits_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Handles the FormClosing event of the frmListenPractice control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.FormClosingEventArgs"/> instance containing the event data.</param>
        private void frmListenPractice_FormClosing(object sender, FormClosingEventArgs e)
        {
            axWMP.Ctlcontrols.pause();

            DialogResult result = MessageBox.Show(message1, thongtin, MessageBoxButtons.YesNoCancel);

            if (DialogResult.No == result)
            {

            }
            else if (DialogResult.Yes == result)
            {
                while (true)
                {
                    saveFileDialogListenPractice.Filter = filelog + "|*.JLP.xml";
                    saveFileDialogListenPractice.Title = luufile;
                    if (DialogResult.OK == saveFileDialogListenPractice.ShowDialog())
                    {
                        if (!JTest.BUS.ListenBUS.saveTestLog(saveFileDialogListenPractice.FileName, PracticeList, strLevel + @"\" + strTopic, "(corrected/Answered/All question) " + trueAns.ToString() + "/" + answered.ToString()))
                        {
                            if (DialogResult.No == MessageBox.Show(message2, baoloi, MessageBoxButtons.YesNo))
                                break;
                        }
                        else
                            break;
                    }
                    else
                        break;
                }
            }
            else
            {
                e.Cancel = true;
                axWMP.Ctlcontrols.play();
            }
        }

        /// <summary>
        /// Handles the MouseHover event of the picBack control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void picBack_MouseHover(object sender, EventArgs e)
        {
            this.picBack.Image = global::JTest.Properties.Resources.back_Over;
        }

        /// <summary>
        /// Handles the MouseLeave event of the picBack control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void picBack_MouseLeave(object sender, EventArgs e)
        {
            this.picBack.Image = global::JTest.Properties.Resources.back;
        }

        /// <summary>
        /// Handles the MouseHover event of the picNext control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void picNext_MouseHover(object sender, EventArgs e)
        {
            this.picNext.Image = global::JTest.Properties.Resources.Next_Over;

        }

        /// <summary>
        /// Handles the MouseLeave event of the picNext control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void picNext_MouseLeave(object sender, EventArgs e)
        {
            this.picNext.Image = global::JTest.Properties.Resources.Next;
        }

        private void picNext_Click(object sender, EventArgs e)
        {
            if (this.listBoxQuestion.SelectedIndex < this.listBoxQuestion.Items.Count - 1)
                this.listBoxQuestion.SelectedIndex++;
        }

        private void picBack_Click(object sender, EventArgs e)
        {
            
            if (listBoxQuestion.SelectedIndex > 0)
                listBoxQuestion.SelectedIndex--;
        }

        private void groupPanel1_SizeChanged(object sender, EventArgs e)
        {
            try
            {
                picBack.Location = new System.Drawing.Point(picBack.Location.X, groupPanel1.Height - 32);
                picNext.Location = new System.Drawing.Point(picNext.Location.X, groupPanel1.Height - 30);
                labelXNoImageMess.Location = new System.Drawing.Point(labelXNoImageMess.Location.X, (groupPanel1.Height / 5) * 3);
                labelXNoImageMess.Width = groupPanel1.Width;
            }
            catch { }
        }

        private void expandablePanel1_ExpandedChanged(object sender, DevComponents.DotNetBar.ExpandedChangeEventArgs e)
        {
            try
            {
                if (expandablePanel1.Expanded)
                {
                    axWMP.Ctlcontrols.pause();
                    groupPanelAnswer.Visible = false;
                }
                else
                {
                    groupPanelAnswer.Visible = true;
                }
            }
            catch { }
        }

        private void butStart_Click(object sender, EventArgs e)
        {
            try
            {
                PracticeList.Clear();
                listBoxQuestion.Items.Clear();
                axWMP.URL = null;
                picQuestion.ImageLocation = null;
                axWMP.Ctlenabled = false;
                string mondai = String.Empty; ;
                if (rad1.Checked)
                    mondai = "1";
                if (rad2.Checked)
                    mondai = "2";
                if (rad3.Checked)
                    mondai = "3";
                string year = String.Empty;
                if (CheckedYears.Count > 0)
                {
                    foreach (string s in CheckedYears)
                    {
                        year += s + @"|";
                    }
                }
                if (String.Compare(year, String.Empty) != 0)
                    year = year.Remove(year.Length - 1);
                string strReg = ".*(";
                strReg += year + ").*mondai\\s?" + mondai;

                Regex regex = new Regex(strReg, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                int i = 1;
                foreach (string item in allPracList)
                {
                    string s = item;
                    s = s.Remove(0, s.Length - (s.Length - s.LastIndexOf(@"\")) + 1);
                    if (regex.IsMatch(s))
                    {
                        JTest.Others.ListenQuestion Question = new Others.ListenQuestion();
                        Question.strfileName = item;
                        Question.getKey();
                        PracticeList.Add(Question);
                        listBoxQuestion.Items.Add(Constant.listenSentence + " " + i.ToString());
                        myBrushList.Add(Brushes.Black);
                        i++;
                    }
                }
                if (PracticeList.Count > 0)
                {
                    groupPanelAnswer.Visible = true;
                    expandablePanel1.Expanded = false;
                    textNumOfQue.Text = PracticeList.Count.ToString();
                    if (listBoxQuestion.Items.Count > 1)
                        listBoxQuestion.SelectedIndex = 0;
                    axWMP.Ctlenabled = true;
                }
                else
                {
                    MessageBox.Show(message3, baoloi);
                }
            }
            catch { }
        }

        private void checkedListBoxYeard_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            try
            {
                if (e.NewValue == CheckState.Checked)
                {
                    CheckedYears.Add(checkedListBoxYeard.SelectedItem.ToString());
                }
                else
                {
                    CheckedYears.Remove(checkedListBoxYeard.SelectedItem.ToString());
                }
            }
            catch { }
        }


    }
}
